import sys
import os
import logging
import json
from typing import Dict, List, Any, Optional

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_数据来源(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None
) -> Dict[str, Any]:
    """
    数据来源 - 指标计算函数
    
    ## 指标说明
    该指标用于确定项目数据的来源是客观数据还是调研数据。
    如果是客观数据来源，则从项目表的obj_data_source字段获取；
    如果是调研数据来源，则直接返回调研数据来源标识。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 5895,
        "questionnaire_ids": [11158, 11159]
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok", 
        "code": 0,
        "result": [
            {
                "calcVals": [
                    {
                        "val": [
                            {
                                "key": "default",
                                "val": "全国高校毕业生就业管理系统"
                            }
                        ]
                    }
                ]
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 数据来源, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()  

        # 1. 查询项目配置信息
        project_sql = """
        SELECT obj_data_source 
        FROM dp_njc.client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        obj_data_source = project_info['obj_data_source']
        
        logger.info(f"项目数据来源配置: obj_data_source={obj_data_source}")

        # 判断数据来源类型
        if obj_data_source and any(keyword in obj_data_source for keyword in ["系统", "平台", "信息网", "服务网"]):
            # 客观数据来源
            data_source = obj_data_source
            logger.info(f"识别为客观数据来源: {data_source}")
        else:
            # 调研数据来源
            data_source = "调研数据来源"
            logger.info(f"识别为调研数据来源: {data_source}")
            return {
                "success": True,
                "message": "ok",
                "code": 0,
                "result": [{
                    "calcVals": [{
                        "val": [{
                            "key": "default",
                            "val": data_source
                        }]
                    }]
                }]
            }

        # 构建返回结果
        logger.info(f"指标 '数据来源' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": [{
                "calcVals": [{
                    "val": [{
                        "key": "default",
                        "val": data_source
                    }]
                }]
            }]
        }

    except Exception as e:
        logger.error(f"计算指标 '数据来源' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 数据来源",
            "code": 500,
            "error": str(e)
        }